﻿using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using admin.WebUI3.Models;
using Microsoft.AspNetCore.Http;
using admin.Bussniess;
using admin.Model;
using System;

namespace admin.WebUI3.Controllers
{
    public class HomeController : Controller
    {

        //首页（系统统计）
        public IActionResult Index()
        {

            return View();
        }

        //登录界面+验证（第二次确认验证）无提示
        public IActionResult Login(string name,string password)
        {
            //连数据库验证

            //HttpContext.Session.SetString("code", "myname");
            Administrator admin = null;
            //第一次启动或刷新后的情况，无seesion取值
            if (name == null)
            {
                ViewData["error"] = 0;
                return View("Login");
            }
            if (name != null)
            {
                var service = new ManagerService();
                //验证返回接收一个错误类型或model，
                admin = service.SignVerify(name, password);
            }
            //登录失败的情况，提示错误信息，保持登录界面
            if (admin == null)
            {
                ViewData["error"] = 1;
                return View("Login");
            }
            //登录成功的情况，拿到admin对象即验证通过
            else
            {
                HttpContext.Response.Cookies.Append("adminName", admin.Name);
                HttpContext.Session.SetString("adminName", admin.Name);
                HttpContext.Session.SetString("adminId", admin.Id);
                ViewData["admin"] = admin;
                ViewData["name"] = admin.Name;

                return View("Index");
            }
        }

        //登陆验证方法（同步ajax）第一次验证提示错误
        public string LoginResult(string name,string pwd)
        {
            var service = new ManagerService();
            var admin = service.QueryAdmin(name);
            if (admin == null)
                return "nameFalse";
            else if (admin.Password != pwd)
                return "passwordFalse";
            else
                return "ok";
        }

        //我的主页
        public IActionResult Home()
        {
            var service = new ManagerService();
            ViewData["allauthor"] = service.GetAllAuthor().Count;
            ViewData["allbook"] = service.GetAllBook().Count;
            ViewData["allorder"] = service.GetAllOrder().Count;
            ViewData["allcustomer"] = service.GetALlCustomer().Count;
            ViewData["allarticle"] = service.GetManuscript().Count;
            ViewData["allsalecount"] = service.GetBookSaleCount();
            return View();
        }


        //用户列表界面
        public IActionResult UserList()
        {
            var service = new ManagerService();
            //var customers = service.GetALlCustomer();
            var userorderlist = service.GetAllCustomerOrder();
            ViewData["name"] = HttpContext.Session.GetString("adminName");  // Cookies.TryGetValue("myCookie", out myCookie);
            return View(userorderlist);
        }

        //用户订单查看
        public IActionResult UserOrderShow(string cid)
        {
            var service = new ManagerService();
            var userorder = service.GetAllCustomerOrder(cid);
            return View("OrderList",userorder);
        }

        //用户编辑界面
        public IActionResult UserEdit(string Cid)
        {
            var service = new ManagerService();
            var user = service.QuerCustomer(Cid);
            return View(user);
        }

        //用户查看界面
        public IActionResult UserShow(string Cid)
        {
            var service = new ManagerService();
            var user = service.QuerCustomer(Cid);
            return View(user);
        }

        //用户提交保存。old版本
        public IActionResult UserSave(string userid, string username, string sex, int age, string mobile, string email, string address)
        {
            var service = new ManagerService();
            var oldUser = service.QuerCustomer(userid);
            var customers = service.GetALlCustomer();
            var TempUser = new Customers();
            TempUser.Cid = userid;
            TempUser.Name = username;
            TempUser.Sex = sex;
            TempUser.Age = age;
            TempUser.Phone = mobile;
            TempUser.Mail = email;
            TempUser.Address = address;
            TempUser.Password = oldUser.Password;
            if (service.UpdateUser(TempUser))
                return View("UserEdit", TempUser);
            else
                return View("UserEdit", oldUser);
        }

        //编辑修改用户信息提交的验证
        public string UserSaveInfo()
        {
            var service = new ManagerService();
            string userinfo = Request.Form["infoitem"];
            string[] info = userinfo.Split(',');
            var oldUser = service.QuerCustomer(info[0]);
            if (oldUser.Name == info[1]&& oldUser.Sex == info[2] && oldUser.Age == int.Parse(info[3])&& oldUser.Phone == info[4]&& oldUser.Mail == info[5]&& oldUser.Address == info[6])
                return "nochange";
            else
            {
                oldUser.Name = info[1];
                oldUser.Sex = info[2];
                oldUser.Age = int.Parse(info[3]);
                oldUser.Phone = info[4];
                oldUser.Mail = info[5];
                oldUser.Address = info[6];
            }
            if (service.UpdateUser(oldUser))
                return "ok";
            else
                return "false";
        }

        //用户密码重置
        public string UserResetPsd()
        {
            string Cid = Request.Form["userid"];
            var service = new ManagerService();
            var oldUser = service.QuerCustomer(Cid);
            var TempUser = new Customers();
            TempUser = oldUser;
            TempUser.Password = "123456";
            if (service.UpdateUser(TempUser))
            {
                return "ok";
            }
            else
            {
                return "false";
            }
        }
        //单删用户
        public string UserDel()
        {
            string Cid = Request.Form["userid"];
            var service = new ManagerService();
            var duser = service.QuerCustomer(Cid);
            if (duser!= null)
            {
                if(service.RemoveUser(duser))
                    return "ok";
            }
            return "false";

        }
        //批量删除用户
        public string UserDelB()
        {
            string delitems = Request.Form["delitems"];
            string [] Cid=delitems.Split(',');
            for(int i = 0; i < Cid.Length ; i++)
            {
                var service = new ManagerService();
                var duser = service.QuerCustomer(Cid[i]);
                if (duser != null)
                {
                    if (service.RemoveUser(duser))
                        continue;
                }
                return "false";
            }
            return "ok";
        }

        


        //管理员列表（未用）
        public IActionResult ManageList()
        {
            var service = new ManagerService();
            var admins = service.GetAllAdmin();
            ViewData["name"] = HttpContext.Session.GetString("adminName");
            return View(admins);
        }

        //管理员添加界面（未用）
        public IActionResult ManageAdd()
        {
            return View();
        }

        //管理员修改密码界面
        public IActionResult ManageChangepd()
        {
            return View();
        }

        //管理员修改个人信息界面
        public IActionResult ManageInformation()
        {
            var service = new ManagerService();
            var admin = service.QueryAdmin(HttpContext.Session.GetString("adminId"));
            return View(admin);
        }

        //管理员提交修改个人信息的验证方法
        public string ManageSaveInformation()
        {
            var service = new ManagerService();
            var oldadmin = service.QueryAdmin(HttpContext.Session.GetString("adminId"));
            string admininfo = Request.Form["infoitem"];
            string[] info = admininfo.Split(',');
            if (oldadmin.Name.Equals(info[0]))
            {
                if (oldadmin.Phone.Equals(info[1]))
                {
                    return "nochange";
                }
            }
            if (oldadmin.Name != info[0])
            {
                if (info[0] == "")
                    return "nameError";
                oldadmin.Name = info[0];
            }
            if (oldadmin.Phone != info[1])
            {
                if (info[1] == "")
                    return "phoneError";
                oldadmin.Phone = info[1];
            }
            if (service.UpdateAdmin(oldadmin) != null)
                return "ok";
            else
                return "false";
        }

        //管理员提交修改个人密码信息的验证方法
        public string ManageSavePassword()
        {
            var service = new ManagerService();
            var oldadmin = service.QueryAdmin(HttpContext.Session.GetString("adminId"));
            string adminpassd = Request.Form["passditem"];
            string[] passd = adminpassd.Split(',');
            if (oldadmin.Password != passd[0])
                return "olderror";
            else if (passd[1] != passd[2])
                return "disagree";
            else if (oldadmin.Password == passd[1])
                return "nochange";
            else
            {
                oldadmin.Password = passd[1];
            }
            if (service.UpdateAdmin(oldadmin) != null)
                return "ok";
            else
                return "errordatabase";

        }


        //作家列表-界面
        public IActionResult AuthorList()
        {
            var service = new ManagerService();
            var authors = service.GetAllAuthorBookFors();
            ViewData["name"] = HttpContext.Session.GetString("adminName");
            return View(authors);
        }

        //作家出书申请查看
        public IActionResult AuthorBookFor(string name)
        {
            var service = new ManagerService();
            var bookfor = service.GetAuthorBookforByName(name);
            return View("BookFor",bookfor);
        }

        //作家已出版书列表
        public IActionResult AuthorBookOuted(string id)
        {
            var service = new ManagerService();
            var booklist = service.GetAuthorBookOuted(id);
            return View("BookList", booklist);
        }

        //作家详细信息-界面
        public IActionResult AuthorShow(string id)
        {
            var service = new ManagerService();
            var author = service.QueryAuthorByID(id);
            return View(author);
        }

        //作家编辑-界面
        public IActionResult AuthorEdit(string id)
        {
            var service = new ManagerService();
            var author = service.QueryAuthorByID(id);
            return View(author);
        }

        //作家编辑保存验证方法
        public string AuthorSaveInfo()
        {
            var service = new ManagerService();
            string userinfo = Request.Form["infoitem"];
            string[] info = userinfo.Split(',');
            var oldAuthor= service.QueryAuthorByID(info[0]);
            if (info[2] == "已签")
                info[2] = "1";
            else if (info[2] == "未签")
                info[2] = "0";
            if (oldAuthor.Name == info[1] && oldAuthor.IsContact==info[2] && oldAuthor.Address == info[3
])
                return "nochange";
            else
            {
                oldAuthor.Name = info[1];
                oldAuthor.IsContact = info[2];
                oldAuthor.Address = info[3];
            }
            if (service.UpdateAuthor(oldAuthor))
                return "ok";
            else
                return "false";
        }

        //作家重置密码方法
        public string AuthorResetPassword()
        {
            var service = new ManagerService();
            var author = service.QueryAuthorByID(Request.Form["authorid"]);
            author.Password = "123456";
            if (service.UpdateAuthor(author))
                return "ok";
            else
                return "false";
        }
         //作家删除方法
        public string AuthorDel()
        {
            var service = new ManagerService();
            var author = service.QueryAuthorByID(Request.Form["authorid"]);
            if (author == null)
                return "false";
            else if (service.RemoveAuthor(author))
                return "ok";
            else return "false";
        }

        //作家批删除方法
        public string AuthorDelB()
        {
            string delitems = Request.Form["delitems"];
            string[] Aid = delitems.Split(',');
            for (int i = 0; i < Aid.Length; i++)
            {
                var service = new ManagerService();
                var dauthor = service.QueryAuthorByID(Aid[i]);
                if (dauthor != null)
                {
                    if (service.RemoveAuthor(dauthor))
                        continue;
                }
                return "false";
            }
            return "ok";
        }

        //出书申请-页面
        public IActionResult BookFor()
        {

            var service = new ManagerService();
            var manuscript = service.GetManuscript();
            ViewData["name"] = HttpContext.Session.GetString("adminName");
            return View(manuscript);
        }

        //文稿删除
        public string ArticleDel()
        {
            var service = new ManagerService();
            var article = service.QueryArticleByID(Request.Form["authorid"]);
            if (article == null)
                return "false";
            else if (service.RemoveArticle(article))
                return "ok";
            else return "false";
        }

        //文稿批量删除
        public string ArticleDelB()
        {
            string delitems = Request.Form["delitems"];
            string[] Aid = delitems.Split(',');
            for (int i = 0; i < Aid.Length; i++)
            {
                var service = new ManagerService();
                var article = service.QueryArticleByID(Aid[i]);
                if (article != null)
                {
                    if (service.RemoveArticle(article))
                        continue;
                }
                return "false";
            }
            return "ok";
        }

        //文稿审核
        public string ArticleCheck(string id)
        {
            var service = new ManagerService();
            var article = service.QueryArticleByID(id);
            if (article == null)
                return "false";
            else
            {
                article.Statu = Request.Form["articlestatu"];
                article.AccessTime = DateTime.Now.ToLocalTime();
                article.AccessName = HttpContext.Session.GetString("adminName");
                if (service.UpdateArticle(article))
                    return "ok";
                else return "false";
            }
        }

        //文稿查看
        public string ArticleLook(DateTime t)
        {
            string mytime = t.ToString("yyyy-MM-dd");
            return mytime;
        }



        //所有图书列表-界面
        public IActionResult BookList()
        {
            var service = new ManagerService();
            var bookList = service.GetAllBook();
            ViewData["name"] = HttpContext.Session.GetString("adminName");
            return View("BookList", bookList);
        }

        //图书增加-页面
        public IActionResult BookAdd()
        {
            return View();
        }

        //图书添加时的保存-方法
        public string BookAddSave()
        {
            //string str = "20070529";
            IFormatProvider format = new System.Globalization.CultureInfo("zh-CN");
            string TarStr = "yyyyMMdd";  //注意这里用到HH
            //DateTime MyDate = DateTime.ParseExact(str, TarStr, System.Globalization.CultureInfo.InvariantCulture);

            string additems = Request.Form["additems"];
            string[] NewBook = additems.Split(',');
            var Book = new Book();
            var service = new ManagerService();
            //bug start 非自增主键，若删除以前，可能造成重复主键ID
            var AllBook = service.GetAllBook();
            Book.Id = (AllBook.Count + 1).ToString();
            //bug end
            Book.Name = NewBook[0];
            Book.Isbn = NewBook[1];
            Book.Type = NewBook[2];
            Book.Inventory = decimal.Parse(NewBook[3]);
            Book.Format = NewBook[4];
            Book.PageCount = NewBook[5];
            Book.WordCount = NewBook[6];
            Book.Price = decimal.Parse(NewBook[7]);
            Book.Fee = decimal.Parse(NewBook[8]);
            Book.Editor = NewBook[9];
            Book.PublicationDate = DateTime.ParseExact(NewBook[10], TarStr, System.Globalization.CultureInfo.InvariantCulture);
            Book.Content = NewBook[11];
            Book.Countsale = "0";
            //验证
            if (service.QueryBookByISBN(Book.Isbn) != null)
                return "errorISBN";
            if (service.QueryBookByName(Book.Name) != null)
                return "errorName";
            if (service.AddBook(Book) == true)
                return Book.Id;
            else
                return "false";
        }
        //图书编辑时的保存-方法
        public string BookEditSave(string id)
        {
            IFormatProvider format = new System.Globalization.CultureInfo("zh-CN");
            string TarStr = "yyyyMMdd";  //注意这里用到HH
            //DateTime MyDate = DateTime.ParseExact(str, TarStr, System.Globalization.CultureInfo.InvariantCulture);

            string additems = Request.Form["additems"];
            string[] NewBook = additems.Split(',');
            var Book = new Book();
            var service = new ManagerService();
            var OldBook = service.QueryBook(id);
            Book.Id = id;
            Book.Name = NewBook[0];
            Book.Isbn = NewBook[1];
            Book.Type = NewBook[2];
            Book.Inventory = decimal.Parse(NewBook[3]);
            Book.Countsale = NewBook[4];
            Book.Format = NewBook[5];
            Book.PageCount = NewBook[6];
            Book.WordCount = NewBook[7];
            Book.Price = decimal.Parse(NewBook[8]);
            Book.Fee = decimal.Parse(NewBook[9]);
            Book.Editor = NewBook[10];
            Book.PublicationDate = DateTime.ParseExact(NewBook[11], TarStr, System.Globalization.CultureInfo.InvariantCulture);
            Book.Content = NewBook[12];
            //验证
            if (Book.Isbn != OldBook.Isbn)
            {
                if (service.QueryBookByISBN(Book.Isbn) != null)
                    return "errorISBN";
            }
            if (Book.Name != OldBook.Name)
            {
                if (service.QueryBookByName(Book.Name) != null)
                    return "errorName";
            }
            if (service.UpdateBook(Book) == true)
                return "true";
            else
                return "false";
        }

        //展示图书详细信息-界面
        public IActionResult BookShow(string id)
        {
            var service = new ManagerService();
            var bookShow = service.QueryBook(id);
            var book = service.QueryBookAndAuthorByISBN(bookShow.Isbn);
            ViewData["name"] = HttpContext.Session.GetString("adminName");
            return View(book);
        }

        //图书信息，BYname
        public IActionResult BookShowByName(string name)
        {
            var service = new ManagerService();
            var bookShow = service.QueryBookByName(name);
            return View("BookShow",bookShow);
        }

        //编辑图书信息-界面
        public IActionResult BookEdit(string id)
        {
            var service = new ManagerService();
            var book = service.QueryBook(id);
            ViewData["bookEdit"] = service.QueryBookAndAuthorByISBN(book.Isbn);
            ViewData["name"] = HttpContext.Session.GetString("adminName");
            return View();
        }

        //编辑图书作者信息
        public IActionResult BookAuthorInfo(string isbn)
        {
            var service = new ManagerService();
            var bookauthor = service.QueryBookAndAuthorByISBN(isbn);
            var allauthor = service.GetAllAuthor();
            for(int i = 0; i < bookauthor.authors.Count; i++)
            {
                allauthor.Remove(bookauthor.authors[i]);
            }
            ViewData["authorlist"] = allauthor;
            return View(bookauthor);
        }
        //图书作者的删除
        public string BookAuthorDel(string aid,string isbn)
        {
            var service = new ManagerService();
            if (service.RemoveBookAuthor(aid, isbn))
                return "ok";
            else
                return "false";
        }
        //图书作者的添加
        public string BookAuthorAdd(string aid,string isbn)
        {
            var service = new ManagerService();
            if (service.AddBookAuthor(aid, isbn))
                return "ok";
            else
                return "false";
        }

        //图书删除-方法
        public bool BookDel(string id)
        {
            var service = new ManagerService();
            var data = service.DelBook(id);
            return data;
        }

        //图书批删除-方法
        public bool BookBatchDel() {
            string delitems = Request.Form["delitems"];
            string[] delBook = delitems.Split(',');
            for (int i = 0; i < delBook.Length; i++)
            {
                var service = new ManagerService();
                ;
                if (service.DelBook(delBook[i])==false)
                {
                    return false;
                }
                else
                    continue;
            }
            return true;
        }


        //订单列表
        public IActionResult OrderList()
        {
            var service = new ManagerService();
            var orders = service.GetAllOrder();
            ViewData["name"] = HttpContext.Session.GetString("adminName");
            return View(orders);
        }

        //订单编辑界面
        public IActionResult OrderEdit(string id)
        {
            var service = new ManagerService();
            var nid = int.Parse(id);
            var order = service.QueryOrderByID(nid);
            return View(order);
        }

        //订单地址修改提交验证方法
        public string OrderSaveInfo()
        {
            var service = new ManagerService();
            string orderinfo = Request.Form["infoitem"];
            string[] info = orderinfo.Split(',');
            var id = int.Parse(info[0]);
            var oldOrder = service.QueryOrderByID(id);

            if (oldOrder.Address == info[1])
                return "nochange";
            else
            {
                oldOrder.Address = info[1];
            }
            if (service.UpdateOrder(oldOrder))
                return "ok";
            else
                return "false";
        }

        //订单删除
        public string OrderDel()
        {
            var service = new ManagerService();
            var id = int.Parse(Request.Form["orderid"]);
            var order = service.QueryOrderByID(id);
            if (order == null)
                return "false";
            else if (service.RemoveOrder(order))
                return "ok";
            else return "false";
        }

        //订单批量删除
        public string OrderDelB()
        {
            string delitems = Request.Form["delitems"];
            string[] Oid = delitems.Split(',');
            for (int i = 0; i < Oid.Length; i++)
            {
                var service = new ManagerService();
                var id = int.Parse(Oid[i]);
                var order = service.QueryOrderByID(id);
                if (order != null)
                {
                    if (service.RemoveOrder(order))
                        continue;
                }
                return "false";
            }
            return "ok";
        }

        //订单审核
        public string OrderCheck(string id)
        {
            var oid = int.Parse(id);
            var service = new ManagerService();
            var order = service.QueryOrderByID(oid);
            var statu = Request.Form["orderstatu"];
            if (order == null)
                return "false";
            else if (statu == "已退货")
            {
                if (order.OrderStatus == "退书中")
                {
                    order.OrderStatus = statu;
                    //退书成功后，书的库存，销量无法更新！！
                    if (service.UpdateOrder(order)&&service.UpdateBookByName(order))
                        return "ok";
                    //false时的回退。。。
                    else return "false";
                }
                return "false";
            }
            else if (statu == "已发货")
            {
                if (order.OrderStatus == "等待发货")
                {
                    order.OrderStatus = statu;
                    if (service.UpdateOrder(order))
                        return "ok";
                    else return "false";
                }
                else return "false";
            }
            else return "false";
        }


        //订单批量审核
        public string OrderCheckB()
        {
            string checkitems = Request.Form["checkitems"];
            string[] Oid = checkitems.Split(',');
            var service = new ManagerService();
            return service.OrderCheckB(Oid);
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
